<!--
 * @Author: your name
 * @Date: 2021-03-31 19:24:39
 * @LastEditTime: 2021-04-02 15:38:30
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue-admin-template-master\src\views\product\components\Spu.vue
-->
<template>
  <div>
    <el-form :model="spuInfo">
      <el-form-item label="SPU名称"
                    label-width="100px">
        <el-input placeholder="SPU名称"
                  v-model="spuInfo.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌"
                    label-width="100px">
        <el-select placeholder="请选择品牌"
                   v-model="spuInfo.tmId">
          <el-option :label="tm.tmName"
                     :value="tm.id"
                     v-for="tm in trademarkList"
                     :key="tm.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述"
                    label-width="100px">
        <el-input placeholder="SPU描述"
                  type="textarea"
                  rows="4"
                  v-model="spuInfo.description"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片"
                    label-width="100px">
        <el-upload action="/dev-api/admin/product/fileUpload"
                   list-type="picture-card"
                   :on-preview="handlePictureCardPreview"
                   :on-remove="handleRemove"
                   :on-success="handleAvatarSuccess"
                   :file-list="imageList">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%"
               :src="dialogImageUrl"
               alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性"
                    label-width="100px">
        <el-select :placeholder="unUseSaleAttrList.length>0?`还有${unUseSaleAttrList.length}个未选择`:'没有啦'"
                   v-model='unUseSaleAttrName'>
          <el-option v-for="attr in unUseSaleAttrList"
                     :key="attr.id"
                     :label="attr.name"
                     :value="`${attr.id}:${attr.name}`">
          </el-option>
        </el-select>
        <el-button type="primary"
                   icon="el-icon-plus"
                   @click="addSpuAttr"
                   :disabled='!unUseSaleAttrName'>添加销售属性</el-button>
        <el-table border
                  :data="spuInfo.spuSaleAttrList"
                  style="width: 100%">
          <el-table-column prop="prop"
                           type="index"
                           align="center"
                           label="序号"
                           width="80">
          </el-table-column>
          <el-table-column prop="saleAttrName"
                           label="属性名"
                           width="150">
          </el-table-column>
          <el-table-column prop="prop"
                           label="属性值名称列表"
                           width="width">
            <template slot-scope="{row,$index}">
              <el-tag :key="spuVal.id"
                      v-for="(spuVal,index) in row.spuSaleAttrValueList"
                      closable
                      :disable-transitions="false"
                      @close="row.spuSaleAttrValueList.splice(index,1)">
                {{spuVal.saleAttrValueName}}
              </el-tag>
              <el-input class="input-new-tag"
                        v-model="row.saleAttrValueName"
                        v-if="row.inputVisible"
                        @keyup.enter.native="handleInputConfirm(row)"
                        @blur="handleInputConfirm(row)"
                        ref="saveTagInput"
                        size="small">
              </el-input>
              <el-button class="button-new-tag"
                         v-else
                         @click="showInput(row)"
                         size="small">+添加</el-button>

            </template>
          </el-table-column>
          <el-table-column prop="prop"
                           label="操作"
                           width="150">
            <template slot-scope="{row,$index}">
              <HintButton type="danger"
                          size="mini"
                          icon="el-icon-delete"
                          title="删除属性"
                          @click="spuInfo.spuSaleAttrList.splice($index,1)"></HintButton>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label-width="100px">
        <el-button type="primary"
                   @click="save">保存</el-button>
        <el-button @click="cancle">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'Spu',
  data () {
    return {
      dialogImageUrl: '',
      dialogVisible: false,

      trademarkList: [],
      saleAttrList: [],
      spuInfo: {
        spuName: '',
        tmId: '',
        description: '',
        spuSaleAttrList: [],
        spuImageList: [],
        cartgroy3Id: "",
      },
      //    spuInfo: {
      //   spuName: "",
      //   description: "",
      //   category3Id: "",
      //   tmId: "",
      //   spuImageList: [],
      //   spuSaleAttrList: [],
      // },
      imageList: [],
      unUseSaleAttrName: '',
      cartgroy3Id: ''
    };
  },
  methods: {
    //删除成功之后的回调
    handleRemove (file, fileList) {
      // console.log(file, fileList);
      this.imageList = fileList
    },
    //上传之前的回调
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //上传成功的回调
    handleAvatarSuccess (res, file, fileList) {
      this.imageList = fileList
    },
    //父组件点击添加是发送请求
    async getSpuListInitData (cartgroy3Id) {
      this.cartgroy3Id = cartgroy3Id
      //http://localhost:9528/dev-api/admin/product/baseTrademark/getTrademarkList  get 
      const resultTrademark = await this.$API.trademark.getList()
      if (resultTrademark.code === 200 || resultTrademark.code === 20000) {
        this.trademarkList = resultTrademark.data
      }
      //http://localhost:9528/dev-api/admin/product/baseSaleAttrList  get
      const resultBaseSale = await this.$API.spu.getSaleAttrList()
      if (resultBaseSale.code === 200 || resultBaseSale.code === 20000) {
        this.saleAttrList = resultBaseSale.data
      }
    },
    //父组件点击修改时发送请求
    async addSpuListInitData (row, cartgroy3Id) {
      this.cartgroy3Id = cartgroy3Id
      //http://localhost:9528/dev-api/admin/product/baseTrademark/getTrademarkList  get 
      const resultTrademark = await this.$API.trademark.getList()
      if (resultTrademark.code === 200 || resultTrademark.code === 20000) {
        this.trademarkList = resultTrademark.data || []
      }
      //http://localhost:9528/dev-api/admin/product/baseSaleAttrList  get
      const resultBaseSale = await this.$API.spu.getSaleAttrList()
      if (resultBaseSale.code === 200 || resultBaseSale.code === 20000) {
        this.saleAttrList = resultBaseSale.data || []
      }
      //http://localhost:9528/dev-api/admin/product/getSpuById/1523 get 
      const resultSpuInfo = await this.$API.spu.get(row.id)
      if (resultSpuInfo.code === 200 || resultSpuInfo.code === 20000) {
        this.spuInfo = resultSpuInfo.data || {}
      }
      //http://localhost:9528/dev-api/admin/product/spuImageList/1523 get 
      const resultImageList = await this.$API.sku.getSpuImageList(row.id)
      if (resultImageList.code === 200 || resultImageList.code === 20000) {
        let imageList = resultImageList.data
        imageList.forEach(item => {
          item.name = item.imgName
          item.url = item.imgUrl
        })
        this.imageList = imageList || []
      }
    },
    //点击添加销售属性
    addSpuAttr () {
      let [baseSaleAttrId, saleAttrName] = this.unUseSaleAttrName.split(':')
      let obj = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      }
      this.spuInfo.spuSaleAttrList.push(obj)
      this.unUseSaleAttrName = ''
    },
    //点击button变成input框
    showInput (row) {
      this.$set(row, 'inputVisible', true)
      this.$set(row, 'saleAttrValueName', '')
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      })
    },
    //失去焦点点击回车保存属性值
    handleInputConfirm (row) {
      let { saleAttrValueName, baseSaleAttrId } = row
      console.log(saleAttrValueName, baseSaleAttrId)
      if (saleAttrValueName.trim() === '') {
        row.saleAttrValueName = ''
        row.inputVisible = false
        return
      }
      let isRes = row.spuSaleAttrValueList.some((item) => item.saleAttrValueName === saleAttrValueName)
      if (isRes) {
        this.$message.error('请不要重复输入')
        row.saleAttrValueName = ''
        return
      }
      let obj = { saleAttrValueName, baseSaleAttrId }
      row.spuSaleAttrValueList.push(obj)
      row.saleAttrValueName = ''
      row.inputVisible = false
    },
    //保存
    async save () {
      let { cartgroy3Id, spuInfo, imageList } = this
      spuInfo.cartgroy3Id = cartgroy3Id
      spuInfo.spuImageList = imageList.map(item => {
        return {
          imgName: item.name,
          imgUrl: item.imgUrl || item.response.data
        }
      })
      spuInfo.spuSaleAttrList.forEach((item) => {
        delete item.inputVisible
        delete item.saleAttrValueName
      })
      try {
        const result = await this.$API.spu.addUpdate(spuInfo)
        if (result.code === 200 || result.code === 20000) {
          this.$message.success('保存成功')
          this.$emit('update:visible', false)
          this.$emit('bankSuncess', spuInfo)
          this.resetDate()
        } else {
          this.$message.error('保存失败')
        }
      } catch (error) {
        this.$message.error('保存失败')
      }
    },
    //初始化数据
    resetDate () {
      this.dialogImageUrl = '',
        this.dialogVisible = false,

        this.trademarkList = [],
        this.saleAttrList = [],
        this.spuInfo = {
          spuName: '',
          tmId: '',
          description: '',
          spuSaleAttrList: [],
          spuImageList: [],
          category3Id: "",
        },
        this.imageList = [],
        this.unUseSaleAttrName = '',
        this.cartgroy3Id = ''
    },
    //点击取消按钮
    cancle () {
      this.$emit('cancleBack')
      this.$emit('update:visible', false)
      this.resetDate()
    }
  },
  computed: {
    unUseSaleAttrList () {
      return this.saleAttrList.filter((item) => this.spuInfo.spuSaleAttrList.every((item1) => item1.saleAttrName !== item.name));
    }
  }
}
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
